package com.mallbook.model.service;

import com.mallbook.model.exception.*;
import com.mallbook.model.pojo.PageBean;
import com.mallbook.model.pojo.User;
import com.mallbook.model.mapper.UserMapper;
import com.mallbook.model.utils.MallDefaultConfig;
import com.mallbook.model.utils.MD5Utils;
import com.mallbook.model.utils.MybatisUtils;
import org.apache.ibatis.exceptions.PersistenceException;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @Author 宋明松
 * @Version V1.0.0
 * @Date 2022-06-25
 * 用户service层
 */
public class UserService {

    /**
     * 新增用户
     *
     * @param name  账号
     * @param pwd   密码
     * @param email 邮箱
     */
    public void register(String name, String pwd, String email) {
        UserMapper userMapper = MybatisUtils.getMappers(UserMapper.class);
        User user = new User();
        user.setUsername(name);
        user.setPassword(pwd);
        user.setEmail(email);
        try {
            int countUsername = userMapper.findUserNumByCondition("username", user.getUsername()); // 账号数量
            int countEmail = userMapper.findUserNumByCondition("email", user.getEmail()); // 邮箱数量
            // 账号名，邮箱不能重复
            if (countEmail != 0) {
                throw new EmailExitsException("邮箱已存在！");
            }
            if (countUsername != 0) {
                throw new AccountExitsException("用户名已存在");
            }
            // 密码加密
            String md5Pwd = MD5Utils.stringToMD5(user.getPassword());
            user.setPassword(md5Pwd);
            // 账号注册时间
            LocalDateTime date = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String setTime = formatter.format(date);
            user.setRegTime(setTime);
            user.setImg(MallDefaultConfig.USER_IMG);
            userMapper.add(user);
        } catch (
                PersistenceException e) {
            e.printStackTrace();
            throw new ServiceException("数据操作异常", e);
        }
    }

    /**
     * 删除用户（逻辑删除） 单条
     *
     * @param id 用户ID
     */
    public void delUser(Integer id) {
        UserMapper userMapper = MybatisUtils.getMappers(UserMapper.class);
        User user = new User();
        user.setState(2);
        try {
            userMapper.update(user, id);
        } catch (
                PersistenceException e) {
            throw new ServiceException("数据操作异常", e);
        }
    }

    /**
     * 批量删除用户（逻辑删除）
     *
     * @param ids 用户ID的集合
     */
    public void delUserMore(List<Integer> ids) {
        UserMapper userMapper = MybatisUtils.getMappers(UserMapper.class);
        User user = new User();
        user.setState(2);
        try {
            userMapper.updateMore(ids, user);
        } catch (
                PersistenceException e) {
            throw new ServiceException("数据操作异常", e);
        }
    }

    /**
     * 是否禁用或启用用户 单条
     *
     * @param id    用户ID
     * @param state 状态 -1 禁用，1 启用
     */
    public void disableUser(Integer id, Integer state) {
        UserMapper userMapper = MybatisUtils.getMappers(UserMapper.class);
        User user = new User();
        user.setState(state);
        try {
            userMapper.update(user, id);
        } catch (
                PersistenceException e) {
            throw new ServiceException("数据操作异常", e);
        }
    }

    /**
     * 是否批量禁用或启用用户
     *
     * @param ids   用户ID的集合
     * @param state 状态 -1 禁用，1 启用
     */
    public void disableUserMore(List<Integer> ids, Integer state) {
        UserMapper userMapper = MybatisUtils.getMappers(UserMapper.class);
        User user = new User();
        user.setState(state);
        try {
            userMapper.updateMore(ids, user);
        } catch (
                PersistenceException e) {
            throw new ServiceException("数据操作异常", e);
        }
    }

    /**
     * 除了 账号 注册时间 积分 其他都可以修改
     *
     * @param pwd   密码
     * @param email 邮箱
     * @param state 状态
     * @param img   图片
     * @param uid   账号ID
     */
    public void updateUser(String pwd, String email, Integer state, String img, Integer uid) {
        UserMapper userMapper = MybatisUtils.getMappers(UserMapper.class);
        User user = new User();
        if (pwd != null) {
            user.setPassword(MD5Utils.stringToMD5(pwd));
        }
        user.setEmail(email);
        user.setState(state);
        user.setImg(img);
        try {
            if (!userMapper.findUserById(uid).getEmail().equals(email)) {
                // 修改邮箱
                int countEmail = userMapper.findUserNumByCondition("email", user.getEmail()); // 邮箱数量
                if (countEmail > 0) {
                    throw new EmailExitsException("邮箱已被使用");
                }
            }
            userMapper.update(user, uid);
        } catch (
                PersistenceException e) {
            throw new ServiceException("数据操作异常", e);
        }
    }

    /**
     * 除了 账号  其他都可以修改[管理员权限】
     *
     * @param email   邮箱
     * @param times   注册时间
     * @param state   状态
     * @param integer 积分
     * @param uid     账号ID
     */
    public void updateUserForAdmin(String email, String times, Integer state, Integer integer, Integer uid) {
        UserMapper userMapper = MybatisUtils.getMappers(UserMapper.class);
        User user = new User();
        user.setEmail(email);
        user.setRegTime(times);
        user.setState(state);
        user.setIntegral(integer);
        try {
            if (!email.equals(userMapper.findUserById(uid).getEmail())) {
                // 修改邮箱
                int countEmail = userMapper.findUserNumByCondition("email", user.getEmail()); // 邮箱数量
                if (countEmail > 0) {
                    throw new EmailExitsException("邮箱已被使用");
                }
            }
            userMapper.update(user, uid);
        } catch (
                PersistenceException e) {
            throw new ServiceException("数据操作异常", e);
        }
    }

    /**
     * 用户登录
     * 前台
     *
     * @param username 用户名
     * @param password 密码
     * @return
     */
    public User login(String username, String password) {
        UserMapper userMapper = MybatisUtils.getMappers(UserMapper.class);
        try {
            // 判断账号是否存在,以及是否被删除
            int userNum = userMapper.findUserNumByCondition("username", username);
            if (userNum == 0) {
                throw new AccountNotExitsException("账号不存在");
            }
            User user = userMapper.findUserByNameAndPwd(username, MD5Utils.stringToMD5(password));
            if (user == null) {
                throw new AccountPwdErrorException("密码错误");
            }
            if (user.getState() == 2) {
                throw new AccountNotExitsException("账号已删除");
            }
            // 登录
            // 判断账号是否被禁用
            if (user.getState() == -1) {
                throw new AccountBanException("账号被禁");
            }
            return user;
        } catch (
                PersistenceException e) {
            throw new ServiceException("数据操作异常", e);
        }
    }

    /**
     * 查询所有用户
     * 后台
     *
     * @return
     */
    public PageBean<User> getAllUsers(Integer pageNum) {

        return PageBeanUsers.getByPage(null, pageNum);
    }

    /**
     * 多条件查询用户
     * 后台
     *
     * @param user 封装的条件信息
     * @return
     */
    public PageBean<User> getUsersByCondition(User user, Integer pageNum) {
        return PageBeanUsers.getByPage(user, pageNum);
    }

    /**
     * 查询个人信息
     *
     * @param id 账号ID
     * @return
     */
    public User getUser(Integer id) {
        UserMapper userMapper = MybatisUtils.getMappers(UserMapper.class);
        try {
            return userMapper.findUserById(id);
        } catch (
                PersistenceException e) {
            throw new ServiceException("数据操作异常", e);
        }
    }

    /**
     * 验证用户信息
     *
     * @param user
     */
    public void checkInfo(User user) {
        UserMapper userMapper = MybatisUtils.getMappers(UserMapper.class);
        try {
            int countUsername = userMapper.findUserNumByCondition("username", user.getUsername()); // 账号数量
            int countEmail = userMapper.findUserNumByCondition("email", user.getEmail()); // 邮箱数量
            // 账号名，邮箱不能重复
            if (countEmail != 0) {
                throw new EmailExitsException("邮箱已存在！");
            }
            if (countUsername != 0) {
                throw new AccountExitsException("用户名已存在");
            }
        } catch (
                PersistenceException e) {
            throw new ServiceException("数据操作异常", e);
        }
    }
}
